// mobile bind
// ============

define(['zepto', 'utils', 'JST', 'sui'], function($, utils, JST){
  return {
    init: function(__CTX__, data) {
      this._CTX_ = __CTX__;
      this.data = data
      
      var categoryDisplay = new Array(),
          categoryValue = new Array();
      $.each(data.categories, function(k, group) {
        categoryDisplay[k] = group.name;
        categoryValue[k] = group.id;
      })
      
      this.categoryDisplay = categoryDisplay;
      this.categoryValue   = categoryValue;
      
      var equipmentValue = new Array(),
          equipmentDisplay = new Array();
      $.each(data.equipments, function(k, group) {
        equipmentDisplay[k] = group.name;
        equipmentValue[k] = group.id;
      })
      
      this.equipmentValue = equipmentValue;
      this.equipmentDisplay   = equipmentDisplay;
      
      this.$bindButton = $('[href="#movement-btn"]')
      this.$bindButton.length ? this.bindTagBindingAction() : void 0
    },

    /**
     * Bind action fired on clicking mobile binding button
     */
    bindTagBindingAction: function() {
      var that = this

      // On binding mobile
      this.$bindButton.on('click', function(e) {
        that.currentBtn = this;
        e.preventDefault()
        var $page = that.compileTagBindingPage()
        $.push.transitionIn($page, function() {
            
            $("#category-picker").picker({
                toolbarTemplate: '<header class="bar bar-nav">\
                                    <button class="button button-link pull-right close-picker">确定</button>\
                                    <h1 class="title">请选择动作类别</h1>\
                                  </header>',
              cols: [{
                  textAlign: 'center',
                  values: that.categoryValue,
                  displayValues: that.categoryDisplay
                }],
              formatValue: function (picker, value, displayValue){
                  $(this.input).next().val(value)
                  return displayValue
              },
            });
            
            $("#equipment-picker").picker({
                toolbarTemplate: '<header class="bar bar-nav">\
                                    <button class="button button-link pull-right close-picker">确定</button>\
                                    <h1 class="title">请选择动作器材</h1>\
                                  </header>',
              cols: [{
                  textAlign: 'center',
                  values: that.equipmentValue,
                  displayValues: that.equipmentDisplay
                }],
              formatValue: function (picker, value, displayValue){
                  $(this.input).next().val(value)
                  return displayValue
              },
            });
            
           /* $("#equipment-picker").picker({
                toolbarTemplate: '<header class="bar bar-nav">\
                <button class="button button-link pull-right close-picker">确定</button>\
                <h1 class="title">器材</h1>\
                </header>',
                cols: [
                  {
                    textAlign: 'center',
                    values: ['iPhone 4', 'iPhone 4S', 'iPhone 5', 'iPhone 5S', 'iPhone 6', 'iPhone 6 Plus', 'iPad 2', 'iPad Retina', 'iPad Air', 'iPad mini', 'iPad mini 2', 'iPad mini 3']
                  }
                ]
              });*/
            
            $page.on('click', '#submit', function(e) {
              e.preventDefault();
              var categoryId = $page.find("input[name='categoryId']").val();
              var equipmentId = $page.find("input[name='equipmentId']").val();
              var name = $page.find("input[name='name']").val();
              
              var submiting = that.submitSearch(categoryId, equipmentId, name)
              $.when(submiting).done(function(data) {
                
                $(that.currentBtn).trigger('binded:searched:movement', [$page, data])
              })
            })
        })
      })

      // On mobile binded
      this.$bindButton.on('binded:searched:movement', function(e, $page, response) {
        
        $page.find(".search-result").remove();
        
        var html = "<div class='search-result'>";
        
        if(response.movements) {
          html = html + "<div class='list-block media-list'><ul>"
          for(var i in response.movements) {
            html = html + '<li class="movement-radio">'
                        + '<label class="label-checkbox item-content">'
                        + '<input type="radio" name="movementId" value='+response.movements[i].id+'>'
                        + '<div class="item-media"><i class="icon icon-form-checkbox"></i></div>'
                        + '<div class="item-inner"><div class="item-title-row">'
                        + '<div class="item-title">'+response.movements[i].name+'</div>'
                        + '</div>'
                        + '<div class="item-subtitle">'+ response.movements[i].summary + '</div>'
                        + '</div>'
                        + '</label>'
                        + '</li>';
          }
          
          html = html + '</ul></div>';
        } else {
          html = html + "<p class='text-center' style='color: #999;'></p>"
        }
        
        html = html + '</div>'
        $page.find(".movement-btn").append(html);
        
        $page.on("click", ".movement-radio", function(e){
          var value = $(this).find("input").val().trim();
          console.log(value);
          that.showModal(value)
        })
        
        // Transition out mobile page
        //var itemDomString = $(JST.mobileItemTpl({ 'tagIds': mobile }))
//        $.push.transitionOut($page, {
//          beforeTransition: function() {
//            
//          }
//        })
      })
    },
    
    showModal: function(value) {
      var that = this;
      var html = '<input name ="groupAmount" placeholder="请输入组数" style="display: block; width: 100%; height: 1.6rem; margin: 0 0 .3rem 0; padding: 0 .4rem; font-size: .7rem;" />' +
                 '<input name ="movementNumber" placeholder="请输入每组动作次数" style="display: block; width: 100%; height: 1.6rem; margin: 0 0 .3rem 0; padding: 0 .4rem; font-size: .7rem;" />' + 
                 '<input name ="maxWeight" placeholder="请输入最大重量" style="display: block; width: 100%; height: 1.6rem; margin: 0 0 .3rem 0; padding: 0 .4rem; font-size: .7rem;" />' + 
                 '<input name ="time" placeholder="请输入计时" style="display: block; width: 100%; height: 1.6rem; margin: 0 0 .3rem 0; padding: 0 .4rem; font-size: .7rem;" />' +
                 '<textarea name="remark" placeholder="请输入备注" rows=3 style="display: block; width: 100%; margin: 0 0 .3rem 0; padding: 0 .4rem; font-size: .7rem;"></textarea>';
      var currentModal = $.modal({
        title:  '添加参数',
        text: html,
        buttons: [
          {
            text: '取消'
          },{
            text: '确定',
            close: false,
            onClick: function() {
              var groupAmount = $("input[name='groupAmount']").val();
              var movementNumber = $("input[name='movementNumber']").val();
              var maxWeight = $('input[name="maxWeight"]').val();
              var time = $('input[name="time"]').val();
              var remark = $('textarea[name="remark"]').val();
              
              if(!groupAmount) {
            	  $("input[name='groupAmount']").val(0);
              } else if(isNaN(groupAmount)) {
                  $.toast("组数请输入数字")
                  return false;
              }
              
              if(!movementNumber) {
            	  $("input[name='movementNumber']").val(0);
              } else if(isNaN(movementNumber)) {
                $.toast("每组次数请输入数字")
                return false;
              }
              
              that.submit(value, groupAmount, movementNumber, maxWeight, time, remark);
              $.closeModal(currentModal)
            }
          }
        ]
      })
    },

    /**
     * Compile mobile binding page and return jQuery object
     */
    compileTagBindingPage: function() {
      var $page = $(JST.movementBtnTpl())
      return $page
    },
    
    submitSearch : function(categoryId, equipmentId, name) {
        var that = this, defer = $.Deferred()
        $.showIndicator()
        $.get(that._CTX_.root + '/movements?filter=true&categoryId=' + categoryId + "&equipmentId=" + equipmentId + "&name=" + name)
          .done(function(response) {
            $.hideIndicator()
            utils.processResult(response, function(result) {
              defer.resolve(result.data)
            }, function(result) {
              $.toast(result.message || '查询失败')
            })
          })
          
        return defer.promise()
    },
    
    submit: function(value, groupAmount, movementNumber, maxWeight, time, remark) {
      var that = this
      var dailyId = $(that.currentBtn).data("daily");
      var type = $(that.currentBtn).data("type");
      var url = that._CTX_.root + '/rounds/'+that.data.roundId+'/batch-coursewares/'+that.data.batchId+'/daily-coursewares/' + dailyId + '/coursewares';
      $.showIndicator()
      $.post(url, {"movementType": type, "movement": value, "groupAmount": !groupAmount ? 0 : groupAmount, "movementNumber": !movementNumber ? 0 : movementNumber, "maxWeight": maxWeight, "time": time, "remark": remark})
      .done(function(response) {
        $.hideIndicator()
        utils.processResult(response, function(result) {
          window.location.reload();
        }, function(result) {
          $.toast(result.message || '提交失败')
        })
      })
    }
  }

})

